package concurrent.printAB;

/**
 * @author why
 * @data 2021/8/4
 *
 * volatile只能保证可见性，保证不了原子性，所以打印交替的时候是不对的 例如顺序不对或可以打印出100  K
 */
public class PrintABVolatile {
    private static final int MAX_PRINT_NUM = 100;
    private static volatile int count = 0;

    public static void printAB() {
        new Thread(() -> {
            while (count < MAX_PRINT_NUM) {
                if (count % 2 == 0) {
                    System.out.println("num:" + count);
                    count++;
                }
            }
        }).start();

        new Thread(() -> {
            while (count < MAX_PRINT_NUM) {
                if (count % 2 == 1) {
                    System.out.println("num:" + count);
                    count++;
                }
            }
        }).start();
    }

    public static void main(String[] args) {
            printAB();
    }
}
